'use client';

import React, { useState, useMemo } from 'react';
import { ChevronLeft, ChevronRight } from 'lucide-react';

export interface NewsItem {
    id: string;
    title: string;
    description: string;
    image?: string;
    link?: string;
}

export interface NewsListProps {
    items?: NewsItem[];
    imageWidth?: number;
    imageHeight?: number;
    itemsPerPage?: number;
    maxDescriptionLength?: number;
}

const DEFAULT_ITEMS: NewsItem[] = [
    {
        id: '1',
        title: '仙山八骏有机茶闪耀 杭州茶博会',
        description: '2025年5月21——25日，第七届中国国际茶叶博览会在杭州国际博览中心盛大举行。第七届中国国际茶叶博览会在杭州国际博览中心盛大举行。际博览中心盛大举行。',
        image: '' // Placeholder
    },
    {
        id: '2',
        title: '仙山八骏有机茶闪耀 杭州茶博会',
        description: '2025年5月21——25日，第七届中国国际茶叶博览会在杭州国际博览中心盛大举行。第七届中国国际茶叶博览会在杭州国际博览中心盛大举行。际博览中心盛大举行。',
        image: '' // Placeholder
    }
];

export default function NewsList({
    items = DEFAULT_ITEMS,
    imageWidth = 400,
    imageHeight = 240,
    itemsPerPage = 3,
    maxDescriptionLength
}: NewsListProps) {
    const [currentPage, setCurrentPage] = useState(1);

    // Calculate pagination based on actual items
    const totalItems = items.length;
    const totalPages = Math.ceil(totalItems / itemsPerPage);

    // Get current page items
    const currentItems = useMemo(() => {
        const startIndex = (currentPage - 1) * itemsPerPage;
        const endIndex = startIndex + itemsPerPage;
        return items.slice(startIndex, endIndex);
    }, [items, currentPage, itemsPerPage]);

    // Handle page change
    const handlePageChange = (page: number) => {
        if (page >= 1 && page <= totalPages) {
            setCurrentPage(page);
        }
    };

    // Generate page numbers to display
    const getPageNumbers = () => {
        const pages: number[] = [];
        const maxPagesToShow = 6;

        if (totalPages <= maxPagesToShow) {
            for (let i = 1; i <= totalPages; i++) {
                pages.push(i);
            }
        } else {
            // Always show first page
            pages.push(1);

            if (currentPage > 3) {
                pages.push(-1); // Ellipsis
            }

            // Show pages around current page
            for (let i = Math.max(2, currentPage - 1); i <= Math.min(totalPages - 1, currentPage + 1); i++) {
                if (!pages.includes(i)) {
                    pages.push(i);
                }
            }

            if (currentPage < totalPages - 2) {
                pages.push(-2); // Ellipsis
            }

            // Always show last page
            if (!pages.includes(totalPages)) {
                pages.push(totalPages);
            }
        }

        return pages;
    };

    return (
        <div className="mx-auto px-4 py-8" style={{ width: maxDescriptionLength ? '100%' : '80%' }}>
            <div className="space-y-12">
                {currentItems.map((item) => (
                    <div key={item.id} className={maxDescriptionLength ? "flex flex-col md:flex-row gap-4" : "flex flex-col md:flex-row gap-16 pb-12 border-b border-[#E5E5E5] last:border-0"}>
                        {/* Image Placeholder */}
                        <div 
                            className="w-full shrink-0 bg-[#7B5228]" 
                            style={{ width: `${imageWidth}px` }}
                        >
                            {item.image && (
                                <img src={item.image} alt={item.title} className="w-full h-auto object-cover" />
                            )}
                        </div>

                        {/* Content */}
                        <div className="flex-1 py-2">
                            <h3 
                                className="text-2xl font-medium text-[#1A1A1A] mb-6 tracking-wide cursor-pointer transition-colors hover:text-[#f7b401]"
                                onClick={() => {
                                    if (item.link) {
                                        window.open(item.link, '_blank', 'noopener,noreferrer');
                                    }
                                }}
                            >
                                {item.title}
                            </h3>
                            <p className="text-[#666666] text-base leading-relaxed">
                                {maxDescriptionLength && item.description.length > maxDescriptionLength
                                    ? item.description.substring(0, maxDescriptionLength) + '...'
                                    : item.description}
                            </p>
                        </div>
                    </div>
                ))}
            </div>

            {/* Pagination */}
            {totalPages > 1 && (
                <div className="mt-16 flex items-center justify-center gap-2 text-sm text-[#666666]">
                    <button
                        className="w-8 h-8 flex items-center justify-center bg-[#F5F5F5] hover:bg-[#E0E0E0] transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                        onClick={() => handlePageChange(currentPage - 1)}
                        disabled={currentPage === 1}
                    >
                        <ChevronLeft className="w-4 h-4" />
                    </button>

                    {getPageNumbers().map((page, index) => (
                        page > 0 ? (
                            <button
                                key={index}
                                className={`w-8 h-8 flex items-center justify-center transition-colors ${page === currentPage
                                    ? 'bg-[#F5B400] text-white'
                                    : 'bg-white hover:bg-[#F5F5F5]'
                                    }`}
                                onClick={() => handlePageChange(page)}
                            >
                                {page}
                            </button>
                        ) : (
                            <span key={index} className="w-8 h-8 flex items-center justify-center">
                                ...
                            </span>
                        )
                    ))}

                    <button
                        className="w-8 h-8 flex items-center justify-center bg-[#F5F5F5] hover:bg-[#E0E0E0] transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                        onClick={() => handlePageChange(currentPage + 1)}
                        disabled={currentPage === totalPages}
                    >
                        <ChevronRight className="w-4 h-4" />
                    </button>

                    <span className="ml-4">
                        {totalItems}条 / 共{totalPages}页
                    </span>
                </div>
            )}
        </div>
    );
}
